package com.wingsboat.common.protect.keyresolver.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.wingsboat.common.protect.annotation.Idempotent;
import com.wingsboat.common.protect.aspect.IdempotentAspect;
import com.wingsboat.common.protect.keyresolver.IdempotentKeyResolver;
import com.wingsboat.common.security.utils.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 用户级别的幂等 Key 解析器，使用方法名 + 方法参数 + userId + userType，组装成一个 Key
 *
 * 为了避免 Key 过长，使用 MD5 进行“压缩”
 *
 * @author 芋道源码
 */
@Component
public class UserIdempotentKeyResolver implements IdempotentKeyResolver, InitializingBean {

    @Autowired
    private IdempotentAspect idempotentAspect;

    @Override
    public String resolver(ProceedingJoinPoint joinPoint, Idempotent idempotent) {
        String methodName = joinPoint.getSignature().toString();
        String argsStr = StrUtil.join(",", joinPoint.getArgs());
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        String userType = SecurityUtils.getLoginUser().getSysUser().getUserType();
        return SecureUtil.md5(methodName + argsStr + userId + userType);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        idempotentAspect.addIdempotentKeyResolver(this);
    }
}
